package wetalk.software.bupt.com.wetalk.application;

import android.content.Context;
import android.os.AsyncTask;
import android.os.PowerManager;
import java.util.HashMap;
import java.util.Map;

import cn.bmob.im.inteface.DownloadListener;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkMsg;
import wetalk.software.bupt.com.wetalk.util.HttpUtil;

/**
 * Created by zhangjie on 2018/3/25.
 */

public class UploadManager extends AsyncTask<String, Integer, String>{
    private Context context;
    private PowerManager.WakeLock mWakeLock;
    private UserManager userManager;
    private WeTalkMsg msg;
    private String local;
    private DownloadListener downloadListener;

    public UploadManager(Context context, WeTalkMsg msg, DownloadListener downloadListener) {
        this.context = context;
        this.msg = msg;
        this.downloadListener = downloadListener;
        // 初始化用户管理
        userManager = UserManager.getInstance(context);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.acquire();
        //开始下载
        if(downloadListener!=null){
            downloadListener.onStart();
        }
    }

    @Override
    protected String doInBackground(String... strings) {
        String url = strings[0];
        local=strings[1];
        Map<String, String> fileMap = new HashMap<>();
        //post commit param
        fileMap.put("file", local);
        String res=HttpUtil.formUpload(url,fileMap);
        return res;
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        if (result .contains("fail")){
            if(downloadListener!=null){
                downloadListener.onError(result);
            }
        }else {
            //更新该消息的下载本地地址
            //WeTalkDB.create(context).updateContentForTargetMsg(local, msg);
            if(downloadListener!=null){
                downloadListener.onSuccess();
            }
        }
    }
}
